class Solution
{
public:
    int minPathCost(vector<vector<int>> &grid, vector<vector<int>> &moveCost)
    {
        int m = grid.size();
        int n = grid[0].size();
        vector<int> dpLast(grid[0]);
        vector<int> dpCur(n);
        for (int curLine = 1; curLine < m; ++curLine)
        {
            for (int i = 0; i < n; ++i)
            {
                int minCost = INT_MAX;
                for (int j = 0; j < n; ++j)
                {
                    int lastLineNode = grid[curLine - 1][j];
                    int cost = moveCost[lastLineNode][i] + dpLast[j] + grid[curLine][i];
                    minCost = min(minCost, cost);
                }
                dpCur[i] = minCost;
            }
            dpCur.swap(dpLast);
        }
        return *min_element(dpLast.begin(), dpLast.end());
    }
};